package untils

import (
	"activity_srv/basic/config"
	"fmt"
)

// 扣减库存
func GoodsStockFormRedis(activityId int) bool {
	key := fmt.Sprintf("goodsId:%d", activityId)
	result, err := config.Rdb.LPop(config.Ctx, key).Result()
	if err != nil {
		return false
	}

	return result == "1"
}

// 同步redis库存
func SyncStockToRedis(activityId int, stock int) (int, error) {
	key := fmt.Sprintf("goodsId:%d", activityId)
	for i := 0; i < stock; i++ {
		config.Rdb.LPush(config.Ctx, key, 1)
	}
	return stock, nil
}

// 增加库存
func IncrStockToRedis(activityId int) {
	key := fmt.Sprintf("goodsId:%d", activityId)
	config.Rdb.LPush(config.Ctx, key, 1)
}

// 获取库存
func GetStockFormRedis(activityId int) int {
	key := fmt.Sprintf("goodsId:%d", activityId)
	stock, err := config.Rdb.LLen(config.Ctx, key).Result()
	if err != nil {
		return 0
	}
	return int(stock)
}
